<template>
  <el-form ref="formRef" :model="formData">
    <el-descriptions class="mb-16" :column="1" :border="true">
      <el-descriptions-item
        label-class-name="desc-label"
        :class-name="['desc-content-1']"
      >
        <template #label>
          {{ props.label }}
          <span v-if="props.required" class="required-mark">*</span>
          <span v-else class="optional-mark">(选填)</span>
        </template>
        <el-form-item :rules="validationRules" :prop="formField">
          <el-input
            type="textarea"
            v-model="inputValue"
            :rows="rows"
            :disabled="disabled"
            :placeholder="placeholder"
            @input="handleInput"
          />
        </el-form-item>
      </el-descriptions-item>
    </el-descriptions>
  </el-form>
</template>

<script setup>
import { computed, ref, watch, reactive } from 'vue';

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  label: {
    type: String,
    default: '审批意见'
  },
  required: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  },
  rows: {
    type: Number,
    default: 2
  },
  placeholder: {
    type: String,
    default: '请输入审批意见'
  },
  formField: {
    type: String,
    default: 'content'
  }
});

const emit = defineEmits(['update:modelValue', 'input']);

// 创建表单引用
const formRef = ref(null);

// 创建表单数据对象，用于验证
const formData = reactive({
  [props.formField]: props.modelValue
});

const inputValue = ref(props.modelValue);

// 监听外部传入的值变化
watch(() => props.modelValue, (newVal) => {
  inputValue.value = newVal;
  formData[props.formField] = newVal;
});

// 监听内部值变化，向外发送更新
watch(inputValue, (newVal) => {
  emit('update:modelValue', newVal);
  formData[props.formField] = newVal;
});

const handleInput = (val) => {
  emit('input', val);
  formData[props.formField] = val;
};

// 根据required属性动态生成校验规则
const validationRules = computed(() => {
  if (props.required) {
    return [
      { required: true, message: `请输入${props.label}`, trigger: 'blur' }
    ];
  }
  return [];
});

// 提供校验方法，供父组件调用
const validateForm = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate((valid) => {
      if (valid) {
        resolve(true);
      } else {
        reject(false);
      }
    });
  });
};

// 暴露方法给父组件
defineExpose({
  validateForm
});
</script>

<style lang="scss" scoped>
@import url('@/views/project/projectDetails/styles/transfer.css');
::v-deep .desc-label {
  width: 210px;
}
// description为1列时content宽度
::v-deep .desc-content-1 {
  width: 900px;
}

.required-mark {
  color: #f56c6c;
  margin-left: 4px;
}
.optional-mark {
  color: #909399;
  font-size: 12px;
  margin-left: 4px;
}
</style>